package leetcode.t2String;

/**
 * 14.最长公共前缀
 * @author K
 * @date 2024/1/23 14:34
 */
public class T14_LongestCommonPrefix {

    public static String longestCommonPrefix(String[] strs) {
        if (strs == null || strs.length == 0) {
            return "";
        }

        //第一层循环第一个单词的字符
        //第二层循环后面单词的字符
        for (int i = 0; i < strs[0].length(); i++) {
            char c = strs[0].charAt(i);
            for (int j = 1; j < strs.length; j++) {
                //i == strs[j].length()代表当前单词没有后面的字符，已经到头了
                if (i == strs[j].length() || c != strs[j].charAt(i)) {
                    return strs[0].substring(0, i);
                }

            }
        }
        return strs[0];
    }

    public static void main(String[] args) {
        String s = longestCommonPrefix(new String[]{"flower", "flow", "flight"});
        String s1 = longestCommonPrefix(new String[]{"dog","racecar","car"});
        String s2 = longestCommonPrefix(new String[]{"","racecar","car"});
        String s3 = longestCommonPrefix(new String[]{"ab", "a"});

        System.out.println();

    }

}
